package com.tri.framework;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.tri.R;


public class GameView extends SurfaceView implements SurfaceHolder.Callback
{
	private GameViewThread m_thread;
	private IState m_state;
	private SpriteAnimation m_spr;
	
	public GameView(Context context)
	{
		super(context);
		
		setFocusable(true);
		
		AppManager.getInstance().setGameView(this);
		AppManager.getInstance().setReSources(getResources());
		
		getHolder().addCallback(this);
		m_thread = new GameViewThread(getHolder(), this);
		
		m_spr = new SpriteAnimation(BitmapFactory.decodeResource(getResources(), R.drawable.walk));
		m_spr.initSpriteData(167, 125, 5, 4);
		
		changeGameState(new IntroState());
	}

	public void onDraw(Canvas canvas)
	{
		canvas.drawColor(Color.BLACK);
		m_state.render(canvas);
		m_spr.Draw(canvas);
		
	}

	public void update()
	{
		m_state.update();
		
		long gamatime = System.currentTimeMillis();
		m_spr.update(gamatime);
	}

	public void changeGameState(IState state)
	{
		if(m_state != null)
			m_state.destory();
		state.init();
		m_state = state;

	}
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		m_state.onKeyDown(keyCode, event);
		return true;
	}

	public boolean onTouchEvent(MotionEvent event)
	{
		m_state.onTouchEvent(event);
		return true;
	}



	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub

	}

	public void surfaceCreated(SurfaceHolder arg0)
	{
		m_thread.setRunning(true);
		m_thread.start();

	}

	public void surfaceDestroyed(SurfaceHolder arg0)
	{
		boolean retry = true;
		m_thread.setRunning(false);
		while(retry)
		{
			try
			{
				m_thread.join();
				retry = false;
			}
			catch(InterruptedException e)
			{

			}
		}
	}

}
